package com.chat.myxmppchat;
import java.util.Collection;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils;
import com.chat.myxmppchat.R;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;


public class XMPPConnectActivity extends Activity {
	
	private XMPPConnection connection;
	private String TAG="XMPPConnectActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.xmppmain);
		connect("liuzhouhua123", "1");
	}
	
	/*
	 * 连接服务器
	 * */
	public boolean ConServer(){
		ConnectionConfiguration configuration=new ConnectionConfiguration("192.168.1.119",9090);
		configuration.setSASLAuthenticationEnabled(false);
		try {
			connection = new XMPPConnection(configuration);
			connection.connect();
		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	
	/*
	 * 注册
	 * @param name 注册帐号 
	 * @param passwd 注册密码 
	 * @return 0、服务器没有返回结果 1、注册成功 2、这个账号已经存在3、注册失败 
	 * */
	public String register(String name,String passwd){
		if(connection==null){
			return "0";
		}
		Registration reg = new Registration();
		reg.setType(IQ.Type.SET);
		reg.setTo(connection.getServiceName());
		reg.setUsername(name);// 注意这里createAccount注册时，参数是username，不是jid，是“@”前面的部分。
		reg.setPassword(passwd);
		reg.addAttribute("android", "geolo_createUser_android");// 这边addAttribute不能为空，否则出错。
		
		PacketFilter filter=new AndFilter(new PacketIDFilter(reg.getPacketID()),
				new PacketTypeFilter(IQ.class));
		PacketCollector collector=connection.createPacketCollector(filter);
		connection.sendPacket(reg);
		IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
		collector.cancel();//停止请求results
		if(result==null){
			Log.e(TAG,"No response fromserver.");
			return "0";
		}else if(result.getType()==IQ.Type.RESULT){
			return "1";
		}else{
			if(result.getError().toString().equalsIgnoreCase("conflict(409)")){
				Log.e(TAG, "IQ.Type.ERROR:"+result.getError().toString());
				return "2";
			}else{
				Log.e(TAG, "IQ.Type>ERROR:"+result.getError().toString());
				return "3";
			}
		}
	}
	
	/*
	 * 登录
	 * */
	public boolean login(String name,String passwd){
		try {
			if(connection==null){
				return false;
			}
			connection.login(name, passwd);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}
	
	/*
	 * 修改密码
	 * */
	public static boolean changePasswd(XMPPConnection connection,String pwd){
		try {
			connection.getAccountManager().changePassword(pwd);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	
	
	/*
	 * 更改用户状态
	 * 
	 * */
	public void setPresence(int code){
		if(connection==null){
			return ;
		}
		Presence presence;
		switch(code){
		case 0:
			presence = new Presence(Presence.Type.available);
			connection.sendPacket(presence);
			Log.v(TAG, "设置在线");
			break;
		case 1:
			presence = new Presence(Presence.Type.available);
			presence.setMode(Presence.Mode.chat);
			connection.sendPacket(presence);
			Log.v(TAG, "设置Q我吧");
			System.out.println(presence.toXML());
			break;
		case 2:
			presence = new Presence(Presence.Type.available);
			presence.setMode(Presence.Mode.dnd);
			connection.sendPacket(presence);
			Log.v(TAG, "设置忙碌");
			System.out.println(presence.toXML());
			break;
		case 3:
			presence = new Presence(Presence.Type.available);
			presence.setMode(Presence.Mode.away);
			connection.sendPacket(presence);
			Log.v(TAG, "设置离开");
			System.out.println(presence.toXML());
			break;
			
		case 4:
			Roster roster=connection.getRoster();
			Collection<RosterEntry> entries = roster.getEntries();
			for(RosterEntry entry : entries){
				presence = new Presence(Presence.Type.available);
				presence.setPacketID(Packet.ID_NOT_AVAILABLE);
				presence.setFrom(connection.getUser());
				presence.setTo(entry.getUser());
				connection.sendPacket(presence);
				System.out.println(presence.toXML());
			}
			
			//向同一用户的其他客户端发送隐身状态
			presence = new Presence(Presence.Type.unavailable);
			presence.setPacketID(Packet.ID_NOT_AVAILABLE);
			presence.setFrom(connection.getUser());
			presence.setTo(StringUtils.parseBareAddress(connection.getUser()));
			connection.sendPacket(presence);
			Log.v(TAG, "设置隐身");
			break;
			
		case 5:
			presence = new Presence(Presence.Type.unavailable);
			connection.sendPacket(presence);
			Log.v(TAG, "设置离线");
			break;
			default:
				break;
		}
	}
	
	
	/*
	 * 删除当前用户（注销）
	 * */
	public static boolean deleteAccount(XMPPConnection connection){
		try {
			connection.getAccountManager().deleteAccount();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	
	
	public void connect(final String uname,final String upasswd){
		
		
		Thread thread=new Thread(new Runnable() {
			
			@Override
			public void run() {
				ConServer();
				register(uname,upasswd);
				login(uname, upasswd);
			}
		});
		
		thread.start();
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
